package com.changzhi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.changzhi.common.constans.Constants;
import com.changzhi.common.constans.RedisConstans;
import com.changzhi.common.exception.ServiceException;
import com.changzhi.common.util.BaseUtil;
import com.changzhi.common.util.DateUtil;
import com.changzhi.ldyl.model.*;
import com.changzhi.ldyl.model.dto.LanternDto;
import com.changzhi.ldyl.model.vo.GiftConfigVo;
import com.changzhi.ldyl.model.vo.LanternVo;
import com.changzhi.ldyl.model.vo.PageVo;
import com.changzhi.ldyl.model.vo.UserVo;
import com.changzhi.mapper.ActivityDataMapper;
import com.changzhi.mapper.ActivityPrizeMapper;
import com.changzhi.mapper.ActivityWalletMapper;
import com.changzhi.service.ActivityService;
import com.changzhi.service.GiftService;
import com.changzhi.service.LanternService;
import com.changzhi.service.UserService;
import com.changzhi.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.Executor;

/**
 * @Description:
 * @author: 小落
 * @date: 2021年01月21日
 */
@Slf4j
@Service
public class LanternServiceImpl implements LanternService {

	@Autowired
	private ActivityDataMapper activityDataMapper;
	@Resource
	private ActivityWalletMapper activityWalletMapper;
	@Autowired
	private UserService userService;
	@Autowired
	private RedisUtil redisUtil;
	@Autowired
	private ActivityService activityService;
	@Autowired
	private GiftService giftService;
	@Resource
	private ActivityPrizeMapper activityPrizeMapper;
	@Resource
	private Executor executor;

	public final static Integer ACTIVITY_ID_3 = 8;
	public final static Integer ACTIVITY_ID_4 = 9;

	//玫瑰目标值
	public final static Integer targetValue = 13140;
	//守护恋语指定礼物id
	//public final static Map<Integer, Integer> GUARD_GIFT_ID_MAP = new HashMap<>();
	//守护恋语活动时间
	public final static Map<String, LocalDateTime> GUARD_TIME_MAP = new HashMap<>();

	//元宵节灯谜答题指定礼物id
	//public final static Map<Integer, Integer> LANTERN_GIFT_ID_MAP = new HashMap<>();
	//元宵节灯谜答题数据
	public static final Map<Integer, ActivityData> DATA_MAP = new HashMap<>();
	//元宵节题目id
	public final static List<Integer> ID_List = new ArrayList<>();
	//元宵节灯谜答题活动时间
	public final static Map<String, LocalDateTime> LANTERN_TIME_MAP = new HashMap<>();

	@PostConstruct
	public void init(){
		/*//活动1 守护恋语初始化....
		redisUtil.del(RedisConstans.ACTIVITY + ACTIVITY_ID_3);
		Activity activity1 = activityService.getActivity(ACTIVITY_ID_3);
		//礼物id
		*//*JSONArray jsonArray1 = JSON.parseArray(activity1.getProperty1());
		for (int i = 0; i < jsonArray1.size(); i++) {
			GUARD_GIFT_ID_MAP.put(jsonArray1.getInteger(i), jsonArray1.getInteger(i));
		}*//*
		//存活动时间
		GUARD_TIME_MAP.put("startTime", activity1.getStartTime());
		GUARD_TIME_MAP.put("endTime", activity1.getEndTime());*/

		/*//活动2 元宵节灯谜初始化...
		redisUtil.del(RedisConstans.ACTIVITY + ACTIVITY_ID_4);
		Activity activity2 = activityService.getActivity(ACTIVITY_ID_4);
		//存活动时间
		LANTERN_TIME_MAP.put("startTime", activity2.getStartTime());
		LANTERN_TIME_MAP.put("endTime", activity2.getEndTime());
		//存储题目
		LambdaQueryWrapper<ActivityData> wrapper = new LambdaQueryWrapper<>();
		wrapper.eq(ActivityData::getActivityId, ACTIVITY_ID_4).eq(ActivityData::getStatus, 1);
		wrapper.last("limit 1000");
		List<ActivityData> dataList = activityDataMapper.selectList(wrapper);
		for (ActivityData activityData : dataList) {
			DATA_MAP.put(activityData.getId(), activityData);
			ID_List.add(activityData.getId());
		}*/
	}

	@Override
	public void doMqDataByUserGift(UserGift userGift) {
		if(userGift.getTotalGiftValue() == 0){
			return;
		}
		//活动期间每送/收情人节限定礼物可获得守护值/爱慕值
		//送礼还可以获得 玫瑰(用于兑换情人节情侣头像框 ）
		//doGuard(userGift);
		doLantern(userGift);
	}

	private void doLantern(UserGift userGift) {
		/*//1.判断是否指定礼物
		if(LANTERN_GIFT_ID_MAP.get(userGift.getGiftId()) == null){
			return;
		}*/
		//2.是否在活动时间内
		if(!DateUtil.isBetweenTime(LANTERN_TIME_MAP.get("startTime"), LANTERN_TIME_MAP.get("endTime"))){
			return;
		}
		Integer value = userGift.getTotalGiftValue();
		String userId = userGift.getUserId();
		//3.增加答题机会
		ActivityWallet userWallet = getActivityWallet(ACTIVITY_ID_4, userId);
		if (userWallet == null && redisUtil.get(RedisConstans.LANTERN_FLAG + userId) == null) {
			userWallet = new ActivityWallet();
			userWallet.setActivityId(ACTIVITY_ID_4);
			userWallet.setUserId(userId);
			userWallet.setAmount1(value);
			activityWalletMapper.insert(userWallet);
			redisUtil.set(RedisConstans.LANTERN_FLAG + userId, 1, RedisConstans.ONE_MONTH);
		} else{
			activityWalletMapper.addAmount1(userWallet.getId(), value);
		}
	}


	private void doGuard(UserGift userGift) {
		//1.判断是否指定礼物
		/*if(GUARD_GIFT_ID_MAP.get(userGift.getGiftId()) == null){
			return;
		}*/
		//2.是否在活动时间内
		if(!DateUtil.isBetweenTime(GUARD_TIME_MAP.get("startTime"), GUARD_TIME_MAP.get("endTime"))){
			return;
		}
		String userId = userGift.getUserId();
		String targetId = userGift.getTargetId();
		Integer value = userGift.getTotalGiftValue() * 10;
		if(value == 0){
			return;
		}
		//3.增加守护值 和 增加玫瑰值
		ActivityWallet userWallet = getActivityWallet(ACTIVITY_ID_3, userId);
		if (userWallet == null) {
			userWallet = new ActivityWallet();
			userWallet.setActivityId(ACTIVITY_ID_3);
			userWallet.setUserId(userId);
			userWallet.setAmount1(value);
			userWallet.setAmount3(userGift.getTotalGiftValue());
			activityWalletMapper.insert(userWallet);
		} else{
			activityWalletMapper.addAmount1AndAmount3(userWallet.getId(), value, userGift.getTotalGiftValue());
		}
		//4.增加爱慕值
		ActivityWallet targetWallet = getActivityWallet(ACTIVITY_ID_3, targetId);
		if (targetWallet == null) {
			targetWallet = new ActivityWallet();
			targetWallet.setActivityId(ACTIVITY_ID_3);
			targetWallet.setUserId(targetId);
			targetWallet.setAmount2(value);
			activityWalletMapper.insert(targetWallet);
		} else{
			activityWalletMapper.addAmount2(targetWallet.getId(), value);
		}
		executor.execute(()->{
			redisUtil.del(RedisConstans.GUARD_RANKING);
			//更新排行榜缓存
			Page<UserVo> page = new Page<>();
			page.setCurrent(1);
			page.setSize(10);
			String item = 0 + "_" + page.getCurrent() + "_" + page.getSize();
			Page<UserVo> pageData = activityWalletMapper.selectLoveRankings(page, ACTIVITY_ID_3, 0);
			for (UserVo record : pageData.getRecords()) {
				if(StringUtils.isBlank(record.getAvatarUrl())){
					record.setAvatarUrl(Constants.DEFAULT_AVATAR);
				}
			}
			if(pageData.getTotal() > 50){
				pageData.setTotal(50);
			}
			PageVo pageVo = new PageVo<>(pageData.getRecords(), pageData.getTotal());
			redisUtil.hset(RedisConstans.GUARD_RANKING, item, pageVo, RedisConstans.ONE_HOUR);
		});
	}

	@Override
	public LanternVo loveInfo(LanternDto lanternDto) {
		String userId = lanternDto.getUserId();
		User user = userService.getUser(lanternDto.getUserId());
		if (user == null) {
			throw new ServiceException("用户不存在");
		}
		LanternVo result = new LanternVo();
		//
		result.setUserId(userId).setAccountId(user.getAccountId()).setNickname(user.getNickname()).setAvatarUrl(StringUtils.isBlank(user.getAvatarUrl()) ? Constants.DEFAULT_AVATAR : user.getAvatarUrl());
		//
		ActivityWallet activityWallet = getActivityWallet(ACTIVITY_ID_3, userId);
		Integer roseValue = 0;
		if (activityWallet == null) {
			result.setGuardValue(0).setLoveValue(0).setRoseValue(0);
		} else{
			roseValue = activityWallet.getAmount3();
			result.setGuardValue(activityWallet.getAmount1()).setLoveValue(activityWallet.getAmount2()).setRoseValue(activityWallet.getAmount3());
		}
		//0=玫瑰不足，1=待领取，2=已领取
		if(redisUtil.get(RedisConstans.LANTERN_RECEIVE_RECORD + "0_" + userId) != null){
			result.setStatus0(2);
		}else if(roseValue < targetValue){
			result.setStatus0(0);
		} else {
			result.setStatus0(1);
		}
		if(redisUtil.get(RedisConstans.LANTERN_RECEIVE_RECORD + "1_" + userId) != null){
			result.setStatus1(2);
		}else if(roseValue < targetValue){
			result.setStatus1(0);
		} else {
			result.setStatus1(1);
		}
		return result;
	}

	@Override
	public PageVo<UserVo> loveRankings(LanternDto lanternDto) {
		Integer type = lanternDto.getType();
		if(type == null){
			throw new ServiceException("类型为空");
		}
		String item = type + "_" + lanternDto.getPageNo() + "_" + lanternDto.getPageSize();
		PageVo<UserVo> pageVo = (PageVo<UserVo>) redisUtil.hget(RedisConstans.GUARD_RANKING, item);
		if(pageVo != null){
			return pageVo;
		}
		Page<UserVo> page = new Page<>();
		page.setCurrent(lanternDto.getPageNo() == null ? 1 : lanternDto.getPageNo());
		page.setSize(lanternDto.getPageSize() == null ? 10 : lanternDto.getPageSize());
		if(page.getCurrent() > 5){
			page.setCurrent(5);
		}
		Page<UserVo> pageData = activityWalletMapper.selectLoveRankings(page, ACTIVITY_ID_3, type);
		for (UserVo record : pageData.getRecords()) {
			if(StringUtils.isBlank(record.getAvatarUrl())){
				record.setAvatarUrl(Constants.DEFAULT_AVATAR);
			}
		}
		if(pageData.getTotal() > 50){
			pageData.setTotal(50);
		}
		pageVo = new PageVo<>(pageData.getRecords(), Long.valueOf(pageData.getTotal()));
		redisUtil.hset(RedisConstans.GUARD_RANKING, item, pageVo, RedisConstans.ONE_HOUR);
		return pageVo;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public GiftConfigVo exchangeAward(LanternDto lanternDto) {
		//1.是否在活动时间内
		if(!DateUtil.isBetweenTime(GUARD_TIME_MAP.get("startTime"), GUARD_TIME_MAP.get("endTime"))){
			throw new ServiceException("不在活动时间内");
		}
		Integer type = lanternDto.getType();
		String userId = lanternDto.getUserId();
		if(type == null){
			throw new ServiceException("类型为空");
		}
		//2.判断是否够玫瑰值
		ActivityWallet activityWallet = getActivityWallet(ACTIVITY_ID_3, userId);
		if (activityWallet == null || activityWallet.getAmount1() < targetValue) {
			throw new ServiceException("玫瑰不足");
		}
		int row = activityWalletMapper.reduceAmount3(activityWallet.getId(), targetValue);
		if(row < 1){
			throw new ServiceException("玫瑰不足");
		}
		//3.查询礼物
		ActivityPrize activityPrize = getActivityPrize(ACTIVITY_ID_3, type);
		if (activityPrize == null) {
			throw new ServiceException("礼物不存在");
		}
		//4.发放头像框
		giftService.savePrize(ACTIVITY_ID_3, userId, activityPrize.getGiftId(), 0, activityPrize.getNum());
		redisUtil.set(RedisConstans.LANTERN_RECEIVE_RECORD + type + "_" + userId, 1, RedisConstans.ONE_MONTH);
		return null;
	}

	@Override
	public LanternVo lanternInfo(LanternDto lanternDto) {
		LanternVo result = new LanternVo();
		String userId = lanternDto.getUserId();
		//是否日榜前三
		ActivityPrize dayPrize = dayRanking(userId);
		result.setDayPrize(dayPrize);
		if(result.getDayPrize() != null){
			return result;
		}
		if(!DateUtil.isBetweenTime(LANTERN_TIME_MAP.get("startTime"), LANTERN_TIME_MAP.get("endTime"))){
			throw new ServiceException("不在活动时间内");
		}
		//题目
		String key = RedisConstans.LANTERN_CURRENT_INFO + userId;
		List<ActivityData> list = redisUtil.get(key);
		if(CollectionUtils.isEmpty(list)){
			list = getRandom(5);
			for (ActivityData activityData : list) {
				activityData.setResult(null);
			}
			//存放当前回合题目到缓存中
			redisUtil.set(key, list);
		}

		List<LanternVo> titleList = new ArrayList<>();
		for (int i = 0; i < list.size(); i++) {
			LanternVo vo = new LanternVo();
			vo.setId(list.get(i).getId());
			vo.setTitle((i+1) + "." + list.get(i).getContent());
			vo.setAnswer0(list.get(i).getProperty0());
			vo.setAnswer1(list.get(i).getProperty1());
			titleList.add(vo);
		}

		//剩余次数和元宵值
		Integer num = 0;
		Integer value = 0;
		ActivityWallet activityWallet = getActivityWallet(ACTIVITY_ID_4, userId);
		if(activityWallet != null){
			num = (activityWallet.getAmount1() / 1000 + activityWallet.getAmount2() - activityWallet.getNum());
			value = activityWallet.getAmount3();
		}
		//返回
		result.setSurplus(num)
				.setValue(value)
				.setDataList(titleList);

		//当日是否首次登录
		String loginKey = RedisConstans.LANTERN_DAY_LOGIN + LocalDate.now().toString() + "_" + userId;
		Integer loginCache = redisUtil.get(loginKey);
		if(loginCache  == null && DateUtil.isBetweenTime(LANTERN_TIME_MAP.get("startTime"), LANTERN_TIME_MAP.get("endTime"))){
			redisUtil.set(loginKey, 1,RedisConstans.ONE_WEEK);
			if (activityWallet == null) {
				activityWallet = new ActivityWallet();
				activityWallet.setActivityId(ACTIVITY_ID_4);
				activityWallet.setUserId(userId);
				activityWallet.setAmount2(1);
				activityWalletMapper.insert(activityWallet);
			} else{
				activityWalletMapper.addAmount2(activityWallet.getId(), 1);
			}
			result.setSurplus(num + 1);
		}
		return result;
	}

	//元宵日榜前三
	private ActivityPrize dayRanking(String userId){
		//当天进来过一次就不进了
		LocalDate now = LocalDate.now();
		String localDate = now.plusDays(-1).toString();
		String key = RedisConstans.LANTERN_RANKING + localDate + "_" + userId;
		if(redisUtil.get(key) != null){
			return null;
		}
		redisUtil.set(key, 1, RedisConstans.ONE_MONTH);
		//
		Activity activity = activityService.getActivity(ACTIVITY_ID_4);
		if(now.isEqual(activity.getStartTime().toLocalDate())){
			return null;
		}
		//
		Set<Object> userIdSet = redisUtil.zRevRange(RedisConstans.LANTERN_DAY_RANKING_VALUE + localDate, 0, 2);
		List<UserVo> list = redisUtil.hMultiGet(RedisConstans.LANTERN_DAY_RANKING + localDate, userIdSet);
		if(!CollectionUtils.isEmpty(list)){
			for (UserVo userVo : list) {
				if(userVo.getUserId().equals(userId)){
					ActivityPrize prize = getActivityPrize(ACTIVITY_ID_4, 8);
					giftService.savePrize(ACTIVITY_ID_4, userVo.getUserId(), prize.getGiftId(),4, prize.getNum());
					return prize;
				}
			}
		}
		return null;
	}

	@Override
	public LanternVo getResult(LanternDto lanternDto) {
		if(!DateUtil.isBetweenTime(LANTERN_TIME_MAP.get("startTime"), LANTERN_TIME_MAP.get("endTime"))){
			throw new ServiceException("不在活动时间内");
		}
		Integer id = lanternDto.getId();
		String userId = lanternDto.getUserId();
		Integer answer = lanternDto.getAnswer();
		Integer finish = lanternDto.getFinish();
		if(id == null){
			throw new ServiceException("id不能为空");
		}
		LanternVo result = new LanternVo();
		String key = RedisConstans.LANTERN_CURRENT_INFO + userId;
		//取题目
		List<ActivityData> titleList = redisUtil.get(key);
		if(CollectionUtils.isEmpty(titleList)){
			throw new ServiceException("当前回合题目不存在");
		}
		//1.是否有答题机会
		ActivityWallet activityWallet = getActivityWallet(ACTIVITY_ID_4, userId);
		if (activityWallet == null) {
			throw new ServiceException("剩余猜灯谜机会不足！");
		}
		Integer num = (activityWallet.getAmount1() / 1000 + activityWallet.getAmount2() - activityWallet.getNum());
		if(num < 1){
			throw new ServiceException("剩余猜灯谜机会不足！");
		}
		//2.判断是否答题正确
		Integer flag = 0;
		ActivityData activityData = DATA_MAP.get(id);
		if(answer != null && answer.equals(activityData.getResult())){
			flag = 1;
		}
		//当前答题记录
		for (ActivityData data : titleList) {
			if(data.getId().equals(id)){
				data.setResult(flag);
			}
		}
		//不传答案情况
		if(answer == null){
//			log.warn("========{}",JSON.toJSONString(DATA_MAP));
//			log.warn("========{}",JSON.toJSONString(activityData));
			if(activityData.getResult() == 0){
				result.setResultArr(new Integer[]{1,0});
			} else {
				result.setResultArr(new Integer[]{0,1});
			}
		}
		redisUtil.set(key, titleList, RedisConstans.ONE_WEEK);
		//3.是否结算
		if(finish != null && finish == 1){
			settlementLantern(userId, key, activityWallet, result);
			//记录答题次数
			activityWalletMapper.addNum(activityWallet.getId(), 1);
		}
		//返回
		result.setResult(flag);
		return result;
	}

	@Override
	public PageVo<UserVo> lanternRankings(LanternDto lanternDto) {
		if(lanternDto.getPageNo() == null){
			lanternDto.setPageNo(1);
		}
		if(lanternDto.getPageSize() == null){
			lanternDto.setPageSize(5);
		}
		if(lanternDto.getPageNo() > 10){
			lanternDto.setPageNo(10);
		}
		Integer type = lanternDto.getType();
		if(type == null){
			throw new ServiceException("类型为空");
		}
		if(type == 0){
			String localDate  = LocalDate.now().toString();
			Set<Object> userIdSet = redisUtil.zRevRange(RedisConstans.LANTERN_DAY_RANKING_VALUE + localDate, 0, 49);
			List<UserVo> list = redisUtil.hMultiGet(RedisConstans.LANTERN_DAY_RANKING + localDate, userIdSet);
			if(CollectionUtils.isEmpty(list)){
				return new PageVo<>(new ArrayList<>(), 0L);
			}
			for (UserVo userVo : list) {
				User user = userService.getUser(userVo.getUserId());
				if(user != null){
					userVo.setAvatarUrl(StringUtils.isBlank(user.getAvatarUrl()) ? Constants.DEFAULT_AVATAR : user.getAvatarUrl());
					userVo.setNickname(user.getNickname());
				}
			}
			PageVo pageVo = BaseUtil.page(list, lanternDto.getPageNo(), lanternDto.getPageSize());
			return pageVo;
		} else {
			Page<UserVo> page = new Page<>(lanternDto.getPageNo(), lanternDto.getPageSize());
			Page<UserVo> pageData = activityWalletMapper.selectLoveRankings(page, ACTIVITY_ID_4, 2);
			for (UserVo record : pageData.getRecords()) {
				if(StringUtils.isBlank(record.getAvatarUrl())){
					record.setAvatarUrl(Constants.DEFAULT_AVATAR);
				}
			}
			if(pageData.getTotal() > 50){
				pageData.setTotal(50);
			}
			PageVo<UserVo> pageVo = new PageVo<>(pageData.getRecords(), pageData.getTotal());
			return pageVo;
		}
	}


	private void settlementLantern(String userId, String key, ActivityWallet activityWallet, LanternVo result){
		List<GiftConfigVo> giftList = new ArrayList<>();
		int correct = 0;
		//4.获取本回合正确题数
		List<ActivityData> results = redisUtil.get(key);
		for (ActivityData data : results) {
			if(data.getResult() != null && data.getResult() == 1){
				correct++;
			}
		}
		if(correct == 0){
			result.setNum(0);
			result.setPrizeList(giftList);
			redisUtil.del(key);
			return;
		}
		//查奖品
		List<ActivityPrize> list = getActivityPrizeList(ACTIVITY_ID_4);
		//增加元宵值
		int value = correct * 10;
		if(value != 0){
			activityWalletMapper.addAmount3(activityWallet.getId(), value);
			executor.execute(()->{
				//存元宵值，按天存储
				User user = userService.getUser(userId);
				if(user == null){
					return;
				}
				LocalDate localDate = LocalDate.now();
				UserVo userVo = (UserVo) redisUtil.hget(RedisConstans.LANTERN_DAY_RANKING + localDate.toString(), userId);
				if(userVo != null){
					userVo.setValue(userVo.getValue() + value);
				} else{
					userVo = new UserVo();
					userVo.setValue(value);
				}
				userVo.setUserId(userId)
						.setAccountId(user.getAccountId())
						.setAvatarUrl(StringUtils.isNotBlank(user.getAvatarUrl()) ? user.getAvatarUrl() : Constants.DEFAULT_AVATAR)
						.setNickname(user.getNickname());
				redisUtil.hset(RedisConstans.LANTERN_DAY_RANKING + localDate.toString(), user.getUserId(), userVo, RedisConstans.ONE_MONTH);
				redisUtil.zIncrScore(RedisConstans.LANTERN_DAY_RANKING_VALUE + localDate.toString(), userId, (long) value, RedisConstans.ONE_MONTH);
			});
		}
		//元宵值
		giftList.add(new GiftConfigVo(-1, -1, "元宵值", "https://res.xbyy.live/user/dressup/fanMji-1612663081055.png", value));
		//免费礼物
		ActivityPrize prize0 = list.get(0);
		giftList.add(new GiftConfigVo(prize0.getGiftId(), 0, prize0.getName(), prize0.getIcon(), correct));
		//总元宵值 判断
		Integer totalValue = activityWallet.getAmount3() + value;
		if(totalValue >= 5250){
			//挂件5	5250
			doPrize(userId, 7, list, giftList);
		} else if(totalValue >= 2750){
			//挂件4	2750
			doPrize(userId, 6, list, giftList);
		} else if(totalValue >= 1250){
			//挂件3	1250
			doPrize(userId, 5, list, giftList);
		} else if(totalValue >= 500){
			//气泡框	达500可获得气泡框（5天）
			doPrize(userId, 2, list, giftList);
			//挂件2	500
			doPrize(userId, 4, list, giftList);
		} else if(totalValue >= 250){
			//头像框	元宵值达250可获得头像框（5天）
			doPrize(userId, 1, list, giftList);
		} else if(totalValue >= 150){
			//挂件1	150
			doPrize(userId, 3, list, giftList);
		}

		int finalCorrect = correct;
		executor.execute(()->{
			//5.1免费礼物
			ActivityPrize activityPrize = list.get(0);
			for (int i = 0; i < finalCorrect; i++) {
				giftService.savePrize(ACTIVITY_ID_4, userId, activityPrize.getGiftId(), 0, activityPrize.getNum());
			}
			//头像框、气泡框、挂件
			for (GiftConfigVo giftConfigVo : giftList) {
				if(giftConfigVo.getType() == 1){
					giftService.savePrize(ACTIVITY_ID_4, userId, giftConfigVo.getGiftId(), 1, giftConfigVo.getNum());
				} else if(giftConfigVo.getType() == 2
						|| giftConfigVo.getType() == 3
						|| giftConfigVo.getType() == 4
						|| giftConfigVo.getType() == 5
						|| giftConfigVo.getType() == 6
						|| giftConfigVo.getType() == 7){
					giftService.saveUserDress(ACTIVITY_ID_4, userId, giftConfigVo.getGiftId(), 1);
				}
			}
			//更新排行榜缓存
			//redisUtil.del(RedisConstans.LANTERN_RANKING);
			/*//更新排行榜缓存
			LanternDto param = new LanternDto();
			param.setPageNo(1);
			param.setPageSize(10);
			param.setActivityId(ACTIVITY_ID_4);
			String item = 0 + "_" + param.getPageNo() + "_" + param.getPageSize();
			Page<UserVo> page = activityWalletMapper.selectLoveRankings(param);
			PageVo pageVo = new PageVo<>(page.getRecords(), page.getTotal());
			redisUtil.hset(RedisConstans.LANTERN_RANKING, item, pageVo, RedisConstans.ONE_HOUR);
			//更新排行榜缓存
			item = 1 + "_" + param.getPageNo() + "_" + param.getPageSize();
			page = activityWalletMapper.selectLoveRankings(param);
			pageVo = new PageVo<>(page.getRecords(), page.getTotal());
			redisUtil.hset(RedisConstans.LANTERN_RANKING, item, pageVo, RedisConstans.ONE_HOUR);*/
		});
		//返回当前回合结果
		redisUtil.del(key);
		result.setPrizeList(giftList);
		result.setNum(correct);
	}

	private void doPrize(String userId, Integer type, List<ActivityPrize> list, List<GiftConfigVo> giftList){
		String key = RedisConstans.LANTERN_PRIZE + type + "_1" + userId;
		if(redisUtil.get(key) == null){
			ActivityPrize prize = list.get(type);
			giftList.add(new GiftConfigVo(prize.getGiftId(), type, prize.getName(), prize.getIcon(), 1));
			redisUtil.set(key, 1 ,RedisConstans.ONE_MONTH);
		}
	}


	//奖品
	private ActivityPrize getActivityPrize(Integer activityId, Integer type){
		LambdaQueryWrapper<ActivityPrize> wrapper = new LambdaQueryWrapper<>();
		wrapper.eq(ActivityPrize::getActivityId, activityId).eq(ActivityPrize::getType, type);
		wrapper.last("limit 1");
		return activityPrizeMapper.selectOne(wrapper);
	}

	//奖品
	private List<ActivityPrize> getActivityPrizeList(Integer activityId){
		LambdaQueryWrapper<ActivityPrize> wrapper = new LambdaQueryWrapper<>();
		wrapper.eq(ActivityPrize::getActivityId, activityId);
		wrapper.orderByAsc(ActivityPrize::getType);
		return activityPrizeMapper.selectList(wrapper);
	}

	//钱包
	private ActivityWallet getActivityWallet(Integer activityId, String userId){
		LambdaQueryWrapper<ActivityWallet> wrapper = new LambdaQueryWrapper<>();
		wrapper.eq(ActivityWallet::getActivityId, activityId).eq(ActivityWallet::getUserId, userId);
		return activityWalletMapper.selectOne(wrapper);
	}

	/**
	 * 随机取num个从0到maxVal的整数。包括零，不包括maxValue
	 * @param num
	 * @return
	 */
	public static List<ActivityData> getRandom(int num){
		List<ActivityData> resultList = new ArrayList<>();
		Collections.shuffle(ID_List);
		for (int i = 0; i < num; i++) {
			ActivityData data = new ActivityData();
			ActivityData activityData = DATA_MAP.get(ID_List.get(i));
			BeanUtils.copyProperties(activityData, data);
			resultList.add(data);
		}
		return resultList;
	}
}
